package com.ruoyi.water.service;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.water.domain.dto.ApiResponse;
import com.ruoyi.water.domain.dto.WaterMeterArchivePageRespDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * 表具档案查询服务（实现文档4.2接口）
 */
@Service
@Slf4j
public class WaterMeterArchiveService {

    @Autowired
    private WaterTokenService waterTokenService;

    @Autowired
    private RestTemplate restTemplate;

    /** 节能平台基础URL */
    @Value("${energy.api.base-url:}")
    private String energyBaseUrl;

    /** 文档4.2接口路径：/api/meter/findByCondition */
    private static final String METER_ARCHIVE_API_PATH = "/api/meter/findByCondition";

    /**
     * 表具档案查询（使用原始QueryParams构建URL）
     * @param rawQueryParams 前端传来的原始QueryParams
     * @return 分页表具档案数据
     */
    public ApiResponse<WaterMeterArchivePageRespDTO> getMeterArchiveList(String rawQueryParams) {
        try {
            // 1. 获取有效Token
            String accessToken = waterTokenService.getEffectiveAccessToken();
            log.info("表具档案查询使用Token：{}（部分隐藏）", hideToken(accessToken));

            // 2. 构建完整URL
            String fullEnergyUrl = energyBaseUrl + METER_ARCHIVE_API_PATH + "?" + rawQueryParams;
            log.info("表具档案查询请求URL：{}", fullEnergyUrl);

            // 3. 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cookie", "Authorization=" + accessToken);
            HttpEntity<Void> requestEntity = new HttpEntity<>(headers);

            // 4. 发送GET请求
            ResponseEntity<ApiResponse<WaterMeterArchivePageRespDTO>> response = restTemplate.exchange(
                    new URI(fullEnergyUrl),
                    HttpMethod.GET,
                    requestEntity,
                    new ParameterizedTypeReference<ApiResponse<WaterMeterArchivePageRespDTO>>() {}
            );

            log.info(response.getBody().toString());

            // 5. 响应校验（与WaterMeterDataService保持一致）
            if (!response.getStatusCode().is2xxSuccessful()) {
                throw new ServiceException("节能平台返回HTTP错误：" + response.getStatusCode());
            }
            ApiResponse<WaterMeterArchivePageRespDTO> energyResp = response.getBody();
            if (energyResp == null || !Boolean.TRUE.equals(energyResp.getSuccess())) {
                throw new ServiceException("节能平台业务失败：" + (energyResp != null ? energyResp.getMessage() : "无响应"));
            }

            // 6. 打印解析成功的日志（与WaterMeterDataService格式保持一致）
            log.info("节能平台表具档案解析成功！总条数：{}，当前页：{}，分页大小：{}",
                    energyResp.getData() != null ? energyResp.getData().getTotal() : 0,
                    energyResp.getData() != null ? energyResp.getData().getCurrent() : 0,
                    energyResp.getData() != null ? energyResp.getData().getSize() : 0);
            return energyResp;

        } catch (URISyntaxException e) {
            log.error("URL格式异常：", e);
            throw new ServiceException("请求URL格式错误：" + e.getMessage());
        } catch (RestClientException e) {
            log.error("HTTP请求异常：", e);
            throw new ServiceException("节能平台请求失败，请稍后重试");
        } catch (Exception e) {
            log.error("查询未知异常：", e);
            throw new ServiceException("表具档案查询失败：" + e.getMessage());
        }
    }

    /**
     * 隐藏Token敏感信息
     */
    private String hideToken(String token) {
        return token == null || token.length() <= 8 ? "******" : token.substring(0, 4) + "******" + token.substring(token.length() - 4);
    }
}